
ConfigPageVars.valueTypes.add("object", "对象", function(valueType) {

	var v = { useInItems:true, metadataOptions:{}, configValueOptions:{}, configValuesOptions:{}, configValueInit:null };

	var valueTypeEditors = "";
	var valueTypeEnums = [];
	var space = $(this);
	ConfigPageVars.valueTypes.each(function() {
		if (this.type == valueType) { return true; }
		valueTypeEnums.push({ type:this.type, name:this.name });
		space.find(".x-dialog").filterOptions("xpopup", "edit")
		.find(".use-in-object.show-in-" + this.type).each(function() {
			valueTypeEditors += this.outerHTML;
			if ($(this).is(":not(.show-in-type)")) { $(this).remove(); }
		});
	});

	// 配置值的初始化处理
	v.configValueInit = function(valueMetadata, generateHtml) {
		if (!valueMetadata) { return; }
		var $configValue = $(this);
		var opts = $configValue.xcall("options");
		// 根据字段列表生成configValue表单
		var $form = $configValue.xcall("panel").find(".combo-form form");
		var configValueJson = $form.serializeJson() || {};
		var html = [];
		$.each(valueMetadata.items||[], function(i, v) {
			html.push(generateHtml("object-field", $.extend({ $options:opts, fieldValue:configValueJson[v.fieldName] }, v)));
		});
		$form.html(html.join("\n"));
    	// 设置metaItems用于生成configText
		opts.metaItems = valueMetadata.items;
		opts.metaConfig = valueMetadata.config;
		// 初始化新生成的configValue表单
		opts.xref.space.xui($form);
		// 更新combocollect类型的configValue的valueField
		if ($configValue.is(".x-combocollect")) {
			opts.valueField = $.zhh.field(valueMetadata, "config.valueField");
		}
	};

	// 配置项的默认值
	v.configValueOptions.onValueChange = function(newValue) {
		var opts = $(this).xcall("options");
		var text = opts.toText.call(this, newValue);
		$(this).closest("form").find(".show-in-type.show-in-" + valueType)
			.find("[textboxname=configText]").xcall("setValue", text);
	};
	v.configValueOptions.onAfterRenderPanel = function(panel) {
    	var panelOpts = $(this).xcall("options");
    	var space = panelOpts.xref.space;
		space.xui(panel);
	};
	v.configValueOptions.onBindEvent = function(panel) {
		var $combo = $(this);
		// 保存按钮
		panel.on("click", ".combo-form a.do-save", function() {
			var form = panel.find(".combo-form form");
			form.form("enableValidation");
			if (!form.form("validate")) { return; }
			var json = form.serializeJson();
			var buffer = {};
			var metaItems = $combo.xcall("options").metaItems;
			if (!metaItems || !metaItems.length) { return; }
			$.each(metaItems, function(i, v) {
				var value = json[this.fieldName];
				if (value == "") { return true; }
				buffer[this.fieldName] = this.valueType == "number" ? value * 1 : value;
			});
			if ($.isEmptyObject(buffer)) { buffer = null; }
			$combo.xcall("setValue", buffer);
			$combo.xcall("hidePanel");
		});
		// 取消按钮
		panel.on("click", ".combo-form a.do-cancel", function() {
			$combo.xcall("hidePanel");
		});
	};
    // value转换为文本, 用于setText调用
	v.configValueOptions.formatter = function(json) {
		if (!json || $.isEmptyObject(json)) { return ""; }
		var opts = $(this).xcall("options");
		var metaItems = opts.metaItems || [];
		var buffer = [];
		$.each(metaItems, function(i, v) {
			var value = json[this.fieldName];
			if (value == "") { return true; }
			buffer.push(this.fieldName + " : " + value);
		});
        return buffer.join(opts.separator);
	};
	v.configValueOptions.toText = function(json) {
		if (!json || $.isEmptyObject(json)) { return ""; }
		var opts = $(this).xcall("options");
		var metaItems = opts.metaItems || [];
		var buffer = [];
		$.each(metaItems, function(i, v) {
			var value = json[this.fieldName];
			if (value == "") { return true; }
			if (this.valueType == "enums") {
				$.each(this.valueMetadata.items, function() {
					if (this.key == String(value)) { value = this.value; return false; }
				});
			}
			buffer.push(this.fieldText + " : " + value);
		});
        return buffer.join(opts.separator);
	};

	// 配置项元数据编辑器
	function doShowFormPanel(panel) {
		panel.find(".combo-items").addClass("hide");
		panel.find(".combo-form").removeClass("hide");
		setTimeout(function() {
			panel.find("input,select,textarea").filter(":visible:first").focus();
		}, 100);
	};
	function doShowItemsPanel(panel) {
		panel.find(".combo-items").removeClass("hide");
		panel.find(".combo-form").addClass("hide");
	};
	function doElemInit(panel) {
    	var panelOpts = $(this).xcall("options");
    	var space = panelOpts.xref.space;
		space.xui(panel);
	};
	v.metadataOptions.onHandleData = function(data) {
		var opts = $(this).xcall("options");
		if (!opts.useFieldType) { return data; }
		var valueField = undefined;
		var textField = undefined;
		$.each(data.items || [], function() {
			if (this.fieldType == "valueField") {
				valueField = this.fieldName;
			} else if (this.fieldType == "textField") {
				textField = this.fieldName;
			}
		});
		if (data.config == undefined) { data.config = {}; }
		if (valueField == undefined) { delete data.config.valueField; } else { data.config.valueField = valueField; }
		if (textField == undefined) { delete data.config.textField; } else { data.config.textField = textField; }
		return data;
	};
	v.metadataOptions.onItemChange = function(newItems, oldItems) {
		var self = this;
		var $combo = $(this);

		// 收集fieldName和fieldText
		var fieldNames = [];
		var fieldTexts = [];
		$.each(newItems||[], function(i, v) {
			fieldNames.push(this.fieldName);
			fieldTexts.push(this.fieldText);
		});
    	// 设置fieldName和fieldText的metaItems用于校验唯一性
    	var $comboForm = $combo.xcall("panel").find(".combo-form form");
    	$comboForm.find("[textboxname=fieldName]").xcall("textbox").validatebox("options").metaItems = fieldNames;
    	$comboForm.find("[textboxname=fieldText]").xcall("textbox").validatebox("options").metaItems = fieldTexts;

		var $form = $combo.closest("form");
		var $configValue = $form.find(".show-in-" + valueType).find("input[textboxname=configValue]");
		if ($configValue.length == 0) { return; }

		var config = $combo.xcall("getData", "config");
		var comboOpts = $combo.xcall("options");
		var configValueOpts = $configValue.xcall("options");
		var items = newItems;
		// 更新combocollect类型的configValue的valueField
		if ($configValue.is(".x-combocollect")) {
			if (config && config.valueField) {
				configValueOpts.valueField = config.valueField;
			} else {
				configValueOpts.valueField = null;
				items = []; // 如果configValue是combocollect就必须要有config.valueField, 否则无法修改/删除/生成描述
			}
		}

		// 根据字段列表重新生成configValue表单
		var data = { items:items, config:config };
		v.configValueInit.call($configValue, data, function(type, data) {
			return comboOpts.generateHtml.call(self, type, data);
		});
    	// 设置metaItems用于生成configDesc
		configValueOpts.metaItems = items;
		configValueOpts.metaConfig = config;
	};
	v.metadataOptions.onShowPanel = function() {
		var me = $(this);
		var items = me.xcall("getData", "items");
		var panel = me.xcall("panel");
		panel.find(".combo-form form").form("disableValidation");
		if (items.length) {
			doShowItemsPanel(panel);
		} else {
			doShowFormPanel(panel);
		}
	};
	v.metadataOptions.onAfterRenderItems = doElemInit;
	v.metadataOptions.onAfterRenderPanel = function(panel) {
		doElemInit.call(this, panel);
		var $form = panel.find(".combo-form form");
		$form.find(".use-in-object").addClass("show-in-type");
		$form.find("input[textboxname=valueType]").xcall("loadData", valueTypeEnums);
	};
	v.metadataOptions.generateHtml = function(type, data) {
        var v = $.data(this, "combocollect");
        var opts = v.options;
		if (type == opts.panelTemplate) {
			data.valueTypeEditors = valueTypeEditors;
		}
		return $.fn.combocollect.defaults.generateHtml.call(this, type, data);
	};
	v.metadataOptions.onBindEvent = function(panel) {
		var self = this;
		var $combo = $(self);
		// 创建按钮
		panel.on("click", ".combo-items a.do-create", function() {
			doShowFormPanel(panel);
			var form = panel.find(".combo-form form");
			form.removeAttr("data-update");
			form.find("[textboxname=fieldName]").xcall("textbox").validatebox("options").metaDefault = null;
			form.find("[textboxname=fieldText]").xcall("textbox").validatebox("options").metaDefault = null;
		});
		// 清除按钮
		panel.on("click", ".combo-items a.do-clear", function() {
			$combo.xcall("setValues", { config:undefined, items:[] });
		});
		// 删除按钮
		panel.on("click", ".combo-item a.do-remove", function(e) {
			var key = $(this).closest(".combo-item").attr("data-key");
			$combo.xcall("removeItem", key);
		});
		// 修改按钮
		panel.on("click", ".combo-item a.do-edit", function(e) {
			var key = $(this).closest(".combo-item").attr("data-key");
			var data = $combo.xcall("getItem", key);
	    	if (data == null) { return; }

			doShowFormPanel(panel);

			var form = panel.find(".combo-form form");
			form.attr("data-update", key);
			form.form("reset").form("load", $.extend({}, data, { valueType:null, valueMetadata:null }));
			form.fillForm({ required:data.required });
			form.find("input[textboxname=valueType]").xcall("setValue", data.valueType);
			form.find(".show-in-type.show-in-" + data.valueType)
				.find("[textboxname=valueMetadata]").xcall("setValue", $.extend(true, {}, data.valueMetadata));
			form.find("[textboxname=fieldName]").xcall("textbox").validatebox("options").metaDefault = data.fieldName;
			form.find("[textboxname=fieldText]").xcall("textbox").validatebox("options").metaDefault = data.fieldText;
		});
		// 保存按钮
		panel.on("click", ".combo-form a.do-save", function() {
			var form = panel.find(".combo-form form");
			form.form("enableValidation");
			if (!form.form("validate")) { return; }
			var json = form.serializeJson();
			var buffer = {};
			if (json.fieldName) { buffer.fieldName = json.fieldName; }
			if (json.fieldText) { buffer.fieldText = json.fieldText; }
			if (json.valueType) { buffer.valueType = json.valueType; }
			if (json.prompt) { buffer.prompt = json.prompt; }
			if (json.valueMetadata) { buffer.valueMetadata = JSON.parse(json.valueMetadata); }
			if (json.required) { buffer.required = json.required == "1"; }
			if (json.fieldType) {
				buffer.fieldType = json.fieldType;
				buffer.required = $.inArray(buffer.fieldType, ["valueField","textField","requiredField"]) >= 0;
			}
			var oldKey = form.attr("data-update");
			if (oldKey) {
				$combo.xcall("updateItem", { key:oldKey, item:buffer });
			} else {
				$combo.xcall("addItem", buffer);
			}
			form.form("reset").form("disableValidation");
			doShowItemsPanel(panel);
		});
		// 取消按钮
		panel.on("click", ".combo-form a.do-cancel", function() {
			doShowItemsPanel(panel);
		});
	};
	v.metadataOptions.formatter = function(data) {
		var items = data && data.items;
    	if (!items || !items.length) { return ""; }
        var opts = $(this).combocollect("options");
        var buffer = [];
        $.each(items, function(i, v) {
        	buffer.push($.zhh.format('{fieldName}({fieldText})', v));
        });
        return buffer.join(opts.separator);
	};

	function resetUniqueValidMetaItems(newItems) {
		var metaConfig = $(this).xcall("options").metaConfig || {};
		// 收集valueFieldItems和textFieldItems
		var valueFieldItems = [];
		var textFieldItems = [];
		$.each(newItems || [], function() {
			for (var k in this) {
				if (k == metaConfig.valueField) {
					valueFieldItems.push(this[k]);
				} else if (metaConfig.textField && k == metaConfig.textField) {
					textFieldItems.push(this[k]);
				}
			}
		});
    	// 设置valueField和textField的metaItems用于校验唯一性
		var $form = $(this).xcall("panel").find(".combo-form form");
		var $valueField = $form.find("[textboxname='"+metaConfig.valueField+"']");
		if ($valueField.length) { $valueField.xcall("textbox").validatebox("options").metaItems = valueFieldItems; }
		if (metaConfig.textField) {
			var $textField = $form.find("[textboxname='"+metaConfig.textField+"']");
			if ($textField.length) { $textField.xcall("textbox").validatebox("options").metaItems = textFieldItems; }
		}
	};
	// configValueOptions  用于config-item页面收集单个configValue, 控件类型是x-comboform
	// configValuesOptions 用于data-dict  页面收集多个configValue, 控件类型是x-combocollect
	v.configValuesOptions.onItemChange = function(newItems, oldItems) {
		var text = $(this).xcall("getText");
		resetUniqueValidMetaItems.call(this, newItems, oldItems);
		var $form = $(this).closest("form");
		var activeLines = $form.find(".show-in-type.show-in-" + valueType);
		var configText = activeLines.find("[textboxname=configText]");
		if (configText.length) {
			configText.xcall("setValue", text);
		} else {
			activeLines.find("[name=configText]").val(text);
		}
	};
	v.configValuesOptions.onShowPanel = v.metadataOptions.onShowPanel;
	v.configValuesOptions.onAfterRenderItems = doElemInit;
	v.configValuesOptions.onAfterRenderPanel = doElemInit;
	v.configValuesOptions.onBindEvent = function(panel) {
		var self = this;
		var $combo = $(self);
		// 创建按钮
		panel.on("click", ".combo-items a.do-create", function() {
			doShowFormPanel(panel);
			// metaConfig = { valueField+:fieldName, textField*:fieldName }
			var config = $combo.xcall("options").metaConfig;
			var $form = panel.find(".combo-form form");
			$form.removeAttr("data-update");
			if (config.valueField) {
				$form.find("[textboxname='"+config.valueField+"']").xcall("textbox").validatebox("options").metaDefault = null;
			}
			if (config.textField) {
				$form.find("[textboxname='"+config.textField+"']").xcall("textbox").validatebox("options").metaDefault = null;
			}
		});
		// 清除按钮
		panel.on("click", ".combo-items a.do-clear", function() {
			$combo.xcall("setValues", { config:undefined, items:[] });
		});
		// 删除按钮
		panel.on("click", ".combo-item a.do-remove", function(e) {
			var key = $(this).closest(".combo-item").attr("data-key");
			$combo.xcall("removeItem", key);
		});
		// 修改按钮
		panel.on("click", ".combo-item a.do-edit", function(e) {
			var key = $(this).closest(".combo-item").attr("data-key");
			var data = $combo.xcall("getItem", key);
	    	if (data == null) { return; }

			doShowFormPanel(panel);

			// metaConfig = { valueField+:fieldName, textField*:fieldName }
			var config = $combo.xcall("options").metaConfig;
			var $form = panel.find(".combo-form form");
			$form.attr("data-update", key);
			$form.form("reset").form("load", $.extend({}, data));
			if (config.valueField) {
				var defValue = data[config.valueField];
				$form.find("[textboxname='"+config.valueField+"']").xcall("textbox").validatebox("options").metaDefault = defValue;
			}
			if (config.textField) {
				var defValue = data[config.textField];
				$form.find("[textboxname='"+config.textField+"']").xcall("textbox").validatebox("options").metaDefault = defValue;
			}
		});
		// 保存按钮
		panel.on("click", ".combo-form a.do-save", function() {
			var form = panel.find(".combo-form form");
			form.form("enableValidation");
			if (!form.form("validate")) { return; }
			
			var json = form.serializeJson();
			var buffer = {};
			var metaItems = $combo.xcall("options").metaItems;
			if (!metaItems || !metaItems.length) { return; }
			$.each(metaItems, function(i, v) {
				var value = json[this.fieldName];
				if (value == "") { return true; }
				buffer[this.fieldName] = this.valueType == "number" ? value * 1 : value;
			});
			if ($.isEmptyObject(buffer)) { buffer = null; }
			var oldKey = form.attr("data-update");
			if (oldKey) {
				$combo.xcall("updateItem", { key:oldKey, item:buffer });
			} else {
				$combo.xcall("addItem", buffer);
			}
			form.form("reset").form("disableValidation");
			doShowItemsPanel(panel);
		});
		// 取消按钮
		panel.on("click", ".combo-form a.do-cancel", function() {
			doShowItemsPanel(panel);
		});
	};
	v.configValuesOptions.generateHtml = function(type, data) {
        var v = $.data(this, "combocollect");
        var opts = v.options;
		if (type == opts.itemTemplate) {
			data.$metaConfig = v.options.metaConfig;
		}
		return $.fn.combocollect.defaults.generateHtml.call(this, type, data);
	};
	v.configValuesOptions.formatter = function(data) {
		var items = data && data.items;
    	if (!items || !items.length) { return ""; }
    	var metaConfig = $(this).xcall("options").metaConfig || {};
        var buffer = [];
        $.each(items, function(i, v) {
        	if (metaConfig.textField) {
            	buffer.push(this[metaConfig.valueField] + " : " + this[metaConfig.textField]);
        	} else {
        		buffer.push(this[metaConfig.valueField]);
        	}
        });
        var opts = $(this).combocollect("options");
        return buffer.join(opts.separator);
	};
	return v;
});


$.extend($.fn.validatebox.defaults.rules, {
	fieldTypeValidate: {
        validator: function(value, param) {
            var opts = $(this).validatebox("options");
			var inputName = $(this).siblings(".textbox-value").prop("name");
			var $target = $(this).closest(".textbox").siblings("[textboxname='"+inputName+"']");
			var items = $target.xcall("getData", "items");
			
			var valueField = 0;
			var textField = 0;
			$.each(items || [], function() {
				if (this.fieldType == "valueField") {
					valueField ++;
				} else if (this.fieldType == "textField") {
					textField ++;
				}
			});

    		if (valueField < 1) {
        		opts.invalidMessage = "必须要有一个[编号字段]";
        		return false;
    		} else if (valueField > 1) {
        		opts.invalidMessage = "只能有一个[编号字段]";
        		return false;
    		}
    		if (textField > 1) {
        		opts.invalidMessage = "只能有一个[名称字段]";
        		return false;
    		}
            return true;
        }
    }
});
